package com.wjk.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;

/**
 * @author: RobertWei
 * time: 2021/8/13    10:14
 * TODO:
 */

public class AuthenticationDemo {

    public static void main(String[] args) {

        //1. 获取SecurityManager

        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");

        //securityManager 有了, 同时也有iniRealm
        SecurityManager securityManager = factory.getInstance();

        //将securityManager存储到SecurityUtils的静态变量中, 全局可用

        SecurityUtils.setSecurityManager(securityManager);


        //2. 根据SecurityManager 获取subject

        Subject subject = SecurityUtils.getSubject();


        //3. 使用subject 进行认证

        UsernamePasswordToken token = new UsernamePasswordToken("root", "admin");

        try {
            subject.login(token);
            System.out.println("认证成功");
        } catch (AuthenticationException e) {
            System.out.println("认证失败"+e.getMessage());
        }

        boolean authenticated = subject.isAuthenticated();
        System.out.println("authenticated = " + authenticated);

        //5.取消认证
        if (authenticated) {
            subject.logout();
        }

    }
}
